package com.topnav.mc.involve.request;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * @Author: kenny
 * @Date: 2024/1/16 14:32
 */
@Slf4j
public class RequestUtils {

    public static void get(String url, int timeout,Map<String, String> paramsMap,
                               OkCallBack successCallBack, OkCallBack failedCallBack,ErrCallBack errCallBack) {
        requestHttp(url, timeout,"GET", paramsMap, null, 0,
                successCallBack,failedCallBack,errCallBack);
    }
    /**
     * 发起请求
     * @param url
     * @param timeout 秒
     * @param successCallBack
     * @param failedCallBack
     */
    public static void post(String url, int timeout,Map<String, String> paramsMap,
                               OkCallBack successCallBack, OkCallBack failedCallBack,ErrCallBack errCallBack) {
        //发起请求
        requestHttp(url, timeout,"POST", paramsMap, null, 0,
                successCallBack,failedCallBack,errCallBack);
/*        if(result!=null) {
            JSONObject resultObj=JSONObject.parseObject(result);
            int code=resultObj.getIntValue("code");
            //未登录时：{"code":1001,"data":{},"msg":"notLoggedIn"}
            if(code==0){//未登录
                successCallBack.onResult(resultObj.toString());
            }else{//其他错误
                failedCallBack.onResult(result);
            }
        }*/
    }

    /**
     * 发送http请求
     * @param serverUrl
     * @param timeout 秒
     * @param requestMethod
     * @param paramsMap
     * @param data
     * @param length
     * @return
     */
    private static void requestHttp(String serverUrl,
                                      int timeout,String requestMethod,
                                      Map<String, String> paramsMap,
                                      byte[] data,
                                      int length,
                                      OkCallBack successCallBack,
                                      OkCallBack failedCallBack,
                                      ErrCallBack errCallBack
                                      ){
        HttpURLConnection connection=null;
        try {
            connection = (HttpURLConnection)getConnection(serverUrl,timeout,requestMethod, paramsMap);
            if(length > 0){
                connection.setRequestProperty("Content-Length", String.valueOf(length));
            }
            connection.connect();

            if(length > 0){
                OutputStream os = connection.getOutputStream();
                os.write(data, 0, length);
                os.flush();
                os.close();
            }

            if (connection.getResponseCode() == 200) {
                InputStream is = connection.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int len = 0;
                byte buffer[] = new byte[1024];
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                is.close();
                baos.close();
                String result = new String(baos.toByteArray(),"utf-8");
                //return result;
                successCallBack.onResult(result);
            } else {//其他错误码
                System.out.println(String.format("err: %s,code:%s",serverUrl,connection.getResponseCode()));
                JSONObject resultObj=new JSONObject();
                resultObj.put("code",connection.getResponseCode());
                resultObj.put("msg",connection.getResponseCode()+"错误！");
                failedCallBack.onResult(resultObj.toString());
                //return resultObj.toString();
            }
        } catch (Exception e) {//连接错误
            e.printStackTrace();
            log.error(e.toString());
            errCallBack.onResult(e);
        } finally {
            if(connection!=null) {
                connection.disconnect();
            }
        }
        //return null;
    }

    /**
     * 获取http连接对象
     * @param serverUrl
     * @param timeout 秒
     * @param requestMethod
     * @param paramsMap
     * @return
     */
    private static URLConnection getConnection(String serverUrl, int timeout,String requestMethod, Map<String, String> paramsMap) {
        timeout = timeout==0?5000:timeout * 1000;
        HttpURLConnection connection = null;
        try {
            //String url1 = URLEncoder.encode(serverUrl);
            URL url = new URL(serverUrl);
            //System.out.println(url);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(requestMethod);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(timeout);
            connection.setRequestProperty("contentType", "UTF-8");
            connection.setRequestProperty("Connection", "close");
            connection.setRequestProperty("Response-Type", "json");
            if(paramsMap != null) {
                for (String key : paramsMap.keySet()) {
                    try {
                        if(paramsMap.get(key) != null){
                            connection.setRequestProperty(key, paramsMap.get(key));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
        }
        return connection;
    }

    /**
     * 回调类
     * @author Administrator
     *
     */
    public static interface OkCallBack{
        public void onResult(String result);
    }

    public static interface ErrCallBack{
        public void onResult(Exception e);
    }
}

